<template>
  <el-form label-width="100px">
    <el-form-item label="SPU 名称"> SPU 名称 </el-form-item>
    <el-form-item label="SKU 名称">
      <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input type="number" v-model="skuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input type="number" v-model="skuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" v-model="skuInfo.skuDesc" placeholder="规格描述" rows="4"></el-input>
    </el-form-item>

    <el-form-item label="平台属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item v-for="attr in attrList" :key="attr.id" :label="attr.attrName">
          <el-select placeholder="请选择" v-model="attr.attrIdAttrValueId">
            <el-option :value="`${item.attrId}:${item.id}`" v-for="item in attr.attrValueList" :key="item.id"
              :label="item.valueName" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item :label="attr.saleAttrName" v-for="attr in spuSaleAttrList" :key="attr.id">
          <el-select placeholder="请选择" v-model="attr.attrIdValueId">
            <el-option v-for="item in attr.spuSaleAttrValueList" :key="item.id" :label="item.saleAttrValueName"
              :value="`${item.baseSaleAttrId}:${item.id}`" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="图片列表">
      <el-table border stripe :data="spuImgList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img width="100" :src="row.imgUrl" alt="">
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tag v-if="row.isDefault">默认图片</el-tag>
            <el-button type="primary" v-else @click="changeDefault(row)">设为默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>







  </el-form>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import { getAttrInfoList, type attrListType, type attrubuteType } from "@/api/attr";
import type { SkuAttrValueListType, SkuInfoItemType, SkuSaleAttrValueListType } from "@/api/sku";
import { ElMessage } from "element-plus";
export default defineComponent({
  name: "SkuForm",
});
</script>

<script setup lang="ts">
import { requestBaseSaleAttrList, requestSpuImgList, requestSpuSaleAttrList, type SpuImgItemType, type SpuImgListType, type SpuInfoType, type SpuSaleAttrItemType, type SpuSaleAttrListType } from "@/api/spu";
import { storeToRefs } from "pinia";
import { requestSaveSkuInfo, type SkuInfoListType } from "@/api/sku";
import useAttrStore from "@/stores/attr";

//1.接受props传值
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();
const spuInfo = props.spuInfo;

//2.接受自定义事件,用来切换组件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();

//3.拿到pinia中的三级分类数据
const attrStore = useAttrStore();
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

/* //获取所有的平台属性
requestAttrList(1id,2id,3id)==>attrListType
//根据spuId获取当前Spu的销售属性  requestSpuSaleAttrList
requestBaseSaleAttrList()===>BaseSaleAttrListType
//根据当前的spuId获取所有图片列表
requestSpuImgList(spuId)===>SpuImgListType */

//初始化收集数据
const skuInfo = ref<SkuInfoItemType>({
  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",

  //需要从props中的spu中直接拿
  spuId: 0,
  tmId: 0,
  category3Id: 0,

  //需要计算收集的
  skuDefaultImg: "",

  //需要计算收集的
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
})


//初始化一些值 保存 初始化请求的数据
const attrList = ref<attrListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])
const spuImgList = ref<SpuImgListType>([])

//请求数据函数
const getInitData = async () => {
  const promise1 = getAttrInfoList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const promise2 = requestSpuSaleAttrList(spuInfo.id as number);
  const promise3 = requestSpuImgList(spuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);

  attrList.value = result[0];
  spuSaleAttrList.value = result[1];
  spuImgList.value = result[2];
};

//初始化
onMounted(() => {
  getInitData()
})

//收集图片 数据
interface ImgListType {
  id: number;
  imgName: string;
  imgUrl: string;
  spuId: number;
}
//定义一个数据,收集选中的图片组成的数据(千万不要修改原来的数组)
const skuImgList = ref<SpuImgListType>([])
const handleSelectionChange = (val: ImgListType[]) => {
  console.log(val);
  // spuImgList.value = val;
  //val的收集就是从spuImgList中收集的,所以收集过来的值类型和我们的类型一模一样,直接赋值收集即可
  skuImgList.value = val;
};

//点击切换默认按钮
const changeDefault = (row: SpuImgItemType) => {
  //排他把其他全部的isDefault设置为false
  spuImgList.value.forEach((item) => {
    item.isDefault = false;
  })
  //给当前的设置为true
  row.isDefault = true;
}

//保存函数
const save = async () => {
  //收集数据
  // 1》整理spu当中传递过来的
  // spuId:'',
  // tmId: '',
  // category3Id: '',
  skuInfo.value.category3Id = props.spuInfo.category3Id as number;
  skuInfo.value.tmId = props.spuInfo.tmId as number;
  skuInfo.value.spuId = props.spuInfo.id as number;

  // 2》整理图片列表
  skuInfo.value.skuImageList = skuImgList.value.map((item) => {
    return {
      // id: 1,
      spuImgId: item.id as number,
      imgName: item.imgName as string,
      imgUrl: item.imgUrl as string,
      /* 图片新增 */
      // name: "string",
      // url: "string",
      // response: "any",
      /* 是否 是默认按钮 */
      isDefault: item.isDefault as boolean,
    }
  })
  // 3》整理平台属性值列表
  //收集平台属性
  attrList.value.forEach((item) => {
    if (item.attrIdAttrValueId) {
      const [attrId, valueId] = item.attrIdAttrValueId.split(":");
      const newAttrObj = {
        attrId: +attrId,
        valueId: +valueId,
      };
      (skuInfo.value.skuAttrValueList as SkuAttrValueListType).push(newAttrObj);
    }
  });

  // 4》整理销售属性值列表
  spuSaleAttrList.value.forEach((item) => {
    if (item.attrIdValueId) {
      const [saleAttrId, saleAttrValueId] = item.attrIdValueId.split(":");
      const newSaleAttrObj = {
        saleAttrId: +saleAttrId,
        saleAttrValueId: +saleAttrValueId,
      };
      (skuInfo.value.skuSaleAttrValueList as SkuSaleAttrValueListType).push(
        newSaleAttrObj
      );
    }
  });



  //发送请求
  try {
    await requestSaveSkuInfo(skuInfo.value);
    ElMessage.success("新增sku成功");
    emit("setState", 0);
  } catch (e) {
    ElMessage.error("新增sku失败");
  }
}

//取消
const cancel = () => {
  emit("setState", 0);
}




//5.收集我们选中的平台属性
/*
  收集的时候只需要某些下拉菜单的
  attrId?: number;//就是平台属性具体某一个下拉数据的attrId
  valueId?: number;//就是平台属性具体某一个下拉数据的id
  //下边都是不需要的
  id?: number;
  skuId?: number;
  attrName?: string;
  valueName?: string;
*/


// 6.收集销售属性
/*
 收集需要的数据是:
  saleAttrValueId?: number;
  saleAttrId?: number;

  //不需要
  id?: number;
  skuId?: number;
  spuId?: number;
  saleAttrName?: string;
  saleAttrValueName?: string;
*/



//7.收集sku图片
/* 
   
  skuId?: number;
  imgName: string;
  imgUrl: string;
  spuImgId?: number;
  isDefault: string;

  //不需要的
  id?: number;

*/



</script>
